package top.qitun.controller;

import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import io.swagger.annotations.ApiOperation;
import top.qitun.api.ShopServiceAPI;
import top.qitun.bizz.order.lineitem.entity.LineItem;
import top.qitun.bizz.order.lineitem.service.impl.LineItemServiceImpl;
import top.qitun.bizz.order.torder.entity.TOrder;
import top.qitun.bizz.order.torder.service.impl.TOrderServiceImpl;
import top.qitun.model.response.ObjectDataResponse;

/**
 * 订单类
 * 
 * @author Cloudwei
 *
 */
@RestController
@RequestMapping(value = "/v1")
public class OrderController {
	Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	private TOrderServiceImpl orderService;
	
    @Autowired
    private LineItemServiceImpl lineItemService;

	@ApiOperation(value = "创建订单", notes = "创建订单")
	@RequestMapping(value = "/order/{tableid}/{clientid}", method = RequestMethod.POST)
	public ObjectDataResponse<TOrder> create(@PathVariable(value = "tableid") Integer tableId,
			@PathVariable(value = "clientid") Integer clientId, @RequestBody List<LineItem> request) {
		String desc = "创建订单";
		try {
			TOrder order = new TOrder();
			order.setTableId(tableId);
			order.setClientId(clientId);
			Date now = new Date();
			order.setCreateTime(now);
			order.setLastUpdateTime(now);
			order.setStatus(0);
			orderService.add(order);
			request.stream().forEach(lineItem -> {
				lineItem.setOrderId(order.getId());
				try {
					lineItemService.add(lineItem);
				} catch (Exception e) {
					logger.error("添加条目失败", e);
				}
//				return lineItem;
			});
			return new ObjectDataResponse<TOrder>(0, desc + "成功", order);
		} catch (Exception e) {
			logger.error(desc + "失败", e);
			return new ObjectDataResponse<>(-1, desc + "失败.请联系客服" + e.getMessage());
		}
	}
}
